package com.sq.partner.manager.service.impl;

import java.util.*;

import javax.annotation.Resource;

import com.sq.partner.manager.common.Config;
import com.sq.partner.manager.common.exception.AppException;
import com.sq.partner.manager.util.WebServiceUtil;
import org.apache.log4j.Logger;
import org.dom4j.*;
import org.springframework.stereotype.Repository;

import com.sq.partner.manager.common.Result;
import com.sq.partner.manager.dao.IGatewayAgentInfoMtDao;
import com.sq.partner.manager.dao.JSCDDao;
import com.sq.partner.manager.mybatis.model.TradAgentInfo;
import com.sq.partner.manager.mybatis.model.TradSaleAgent;
import com.sq.partner.manager.service.JSCDService;
import com.sq.partner.manager.util.JsonUtils;
import com.sq.partner.manager.util.LogUtil;
import com.sq.partner.manager.util.StrUtil;
/***
 * 急速出单
 * @author menyanlei
 *
 */
@Repository
public class JSCDServiceImpl implements JSCDService {
	private static Logger logger = LogUtil.getLog(JSCDServiceImpl.class); 
	@Resource
	private IGatewayAgentInfoMtDao agentInfoMtDao;
	@Resource
	private JSCDDao JSCDDao;
	@Override
	public Result saveAgentMtInfo(TradAgentInfo agentMtInfo,String saleArry,String prodSet) throws Exception {
		//查询key1---key5是否已经存在
		Map<String, String> map = new HashMap<String, String>();
		String prodStr="";
		if(StrUtil.isNotEmpty(prodSet)){
			List<String> prodlist = Arrays.asList(prodSet.split(","));
			for (int i = 0; i < prodlist.size(); i++) {
				prodStr += "'"+prodlist.get(i)+"',";
			}
			prodStr = prodStr.substring(0,prodStr.length()-1);
		}
		map.put("prodStr",prodStr);
		map.put("productType",agentMtInfo.getProductType());
	/*	map.put("channelCode", agentMtInfo.getChannelCode());*/
		map.put("key1", agentMtInfo.getKey1());
		map.put("key2", agentMtInfo.getKey2());
		if( StrUtil.isEmpty(agentMtInfo.getKey3())){
			agentMtInfo.setKey3("");
		}
		if( StrUtil.isEmpty(agentMtInfo.getKey4())){
			agentMtInfo.setKey4("");
		}
		if( StrUtil.isEmpty(agentMtInfo.getKey5())){
			agentMtInfo.setKey5("");
		}
		map.put("key3", agentMtInfo.getKey3());
		map.put("key4", agentMtInfo.getKey4());
		map.put("key5", agentMtInfo.getKey5());
		/**车意联合*/
		map.put("unionType", agentMtInfo.getUnionType());
		/**销售落地数据对应的产品类型*/
		map.put("productType", agentMtInfo.getProductType());
		map.put("channelCode", agentMtInfo.getChannelCode());
		List<TradAgentInfo> list=agentInfoMtDao.queryAgentInByMap(map);
		/**已存在key值更新*/
		if(list.size()>0){
			logger.info("key值重复更新");
			/**更新不更新合作伙伴代码*/
			agentMtInfo.setChannelCode(null);
			agentMtInfo.setId(list.get(0).getId());
			agentMtInfo.setOperTime(new Date());
			if(agentInfoMtDao.updateAgentInfo(agentMtInfo)){
				map.put("id", agentMtInfo.getId()+"");
				/**删除方案关联信息*/
				JSCDDao.delTradAgentInfoRelaByJSCD(map);
				/**重新插入关联信息**/
				JSCDDao.JSCDAgentInfoRela(map);
				logger.info("操作数据id"+agentMtInfo.getId());
				List<Map<String,String>> listJson = null;
				System.out.println(agentMtInfo.getDptCde().substring(0,2));
				if("44".equals(agentMtInfo.getDptCde().substring(0,2)) && StrUtil.isNotEmpty(saleArry)){
					listJson = JsonUtils.parseJson(saleArry, ArrayList.class);
					List<TradSaleAgent> planSales=new ArrayList<TradSaleAgent>();
					if( listJson != null && listJson.size()!=0){
						/*删除销售信息*/
						agentInfoMtDao.deleteTrade(String.valueOf(agentMtInfo.getId()));
						for (Map<String, String> map2 : listJson) {
							TradSaleAgent planSale=new TradSaleAgent();
							planSale.setAgentFee((Double.parseDouble(map2.get("agentFee"))+""));
							planSale.setAgentNo(map2.get("agentNo"));
							planSale.setEmpNo(map2.get("empNo"));
							planSale.setPersonType(map2.get("personType"));
							planSale.setPracticeNo(map2.get("practiceNo"));
							planSale.setSalePerson(map2.get("salePerson"));
							planSale.setSaleType(map2.get("saleType"));
							planSale.setSeqNo(map2.get("seqNo"));
							planSale.setPlanType(map2.get("planType"));
							planSale.setAgentCode(map2.get("agentCode"));
							planSale.setAgentName(map2.get("agentName"));
							planSale.setSaleName(map2.get("saleName"));
							planSale.setId(agentMtInfo.getId());
							planSale.setInsertDate(new Date());
							planSales.add(planSale);
						}
						agentInfoMtDao.addTrade(planSales);
					}
				}
				return	Result.success("操作成功");
			}else{
				return	Result.error("操作失败");
			}
		}else {
			logger.info("数据库中不存在key插入");
			if(agentInfoMtDao.addAgentInfo(agentMtInfo)){
				if(JSCDDao.JSCDAgentInfoRela(map)){
					logger.info("操作数据id"+agentMtInfo.getId());
					List<Map<String,String>> listJson = null;
					System.out.println(agentMtInfo.getDptCde().substring(0,2));
					if("44".equals(agentMtInfo.getDptCde().substring(0,2)) && StrUtil.isNotEmpty(saleArry)){
						listJson = JsonUtils.parseJson(saleArry, ArrayList.class);
						List<TradSaleAgent> planSales=new ArrayList<TradSaleAgent>();
						if( listJson != null && listJson.size()!=0){
							/*删除销售信息*/
							agentInfoMtDao.deleteTrade(String.valueOf(agentMtInfo.getId()));
							for (Map<String, String> map2 : listJson) {
								TradSaleAgent planSale=new TradSaleAgent();
								planSale.setAgentFee((Double.parseDouble(map2.get("agentFee"))+""));
								planSale.setAgentNo(map2.get("agentNo"));
								planSale.setEmpNo(map2.get("empNo"));
								planSale.setPersonType(map2.get("personType"));
								planSale.setPracticeNo(map2.get("practiceNo"));
								planSale.setSalePerson(map2.get("salePerson"));
								planSale.setSaleType(map2.get("saleType"));
								planSale.setSeqNo(map2.get("seqNo"));
								planSale.setPlanType(map2.get("planType"));
								planSale.setAgentCode(map2.get("agentCode"));
								planSale.setAgentName(map2.get("agentName"));
								planSale.setSaleName(map2.get("saleName"));
								planSale.setId(agentMtInfo.getId());
								planSale.setInsertDate(new Date());
								planSales.add(planSale);
							}
							agentInfoMtDao.addTrade(planSales);
						}
					}
					return Result.success("操作成功");
				}else{
					return Result.error("操作失败");	
				}
			}else{
				return Result.error("操作失败");
			}
		}
	}
	@Override
	public Result queryAgentAndAgreeInfo(String COMCODE, String TEAMCODE,
										 String BUSINESSSOURCE, String CHANNELNAME, String PRODCODE,String empNo,String agentCode)
			throws Exception {
		String url = Config.getProp("SALES_WEBSERVICE_URL");
		String method = Config.getProp("queryAgentAndAgreeInfo_METHOD");
		String namespace = Config.getProp("queryAgentAndAgreeInfo_NAMESPACE");

		//拼接请求报文
		String reqXml =
				"<?xml version=\"1.0\" encoding=\"GBK\"?>" +
						"<XML>" +
						"<AGENT>" +
						//归属机构代码(必传)
						"<COMCODE>"+ COMCODE +"</COMCODE>" +
						//团队代码(必传)
						"<TEAMCODE>"+ TEAMCODE +"</TEAMCODE>" +
						//业务来源(必传)
						"<BUSINESSSOURCE>"+ BUSINESSSOURCE +"</BUSINESSSOURCE>" +
						//渠道名称(必传)
						"<CHANNELNAME>"+ CHANNELNAME +"</CHANNELNAME>" +
						//产品代码(必传)
						"<PRODCODE>"+ PRODCODE +"</PRODCODE>" +
						//中介代码(校验使用)
						"<AGENTCODE></AGENTCODE>" +
						//业务员名称
						"<USERCODE>"+ empNo +"</USERCODE>" +
						"</AGENT>" +
						"</XML>";
		logger.info("查询中介-协议信息--》请求报文:"+reqXml);

		String respXml = "";
		try{
			//调用销管接口
			respXml = WebServiceUtil.call(reqXml, url, method, namespace);
			logger.info("查询中介-协议信息--》返回报文:"+respXml);
		}catch(Exception e){
			logger.info("调用销管接口获取数据异常",e);
			throw new AppException("调用销管接口获取数据异常:" , e);
		}

		// 解析响应报文
		Document document=null;
		try {
			document = DocumentHelper.parseText(respXml);
		} catch (DocumentException e) {
			logger.info("解析销管返回报文异常",e);
			throw new AppException("解析销管返回报文异常:" , e);
		}
		Element root  = document.getRootElement();
		Element RETURN = root.element("RETURN");
		String RETURNCODE = RETURN.elementTextTrim("RETURNCODE");
		Element RETURNMSG = RETURN.element("RETURNMSG");

		//存放代理、协议信息的List
		List<Map<String,Object>> AGENTAGREEMENTList = new ArrayList<Map<String,Object>>();
		if("0000".equals(RETURNCODE)){//成功
			Set <String> prodSet= new HashSet<String>();//用来保存所有销管返回4位产品代码；
			List<Element> AGENTAGREEMENT_elementList = RETURNMSG.elements("AGENT-AGREEMENT");
			for (Element AGENTAGREEMENT_element : AGENTAGREEMENT_elementList) {
				String AGENTCODE = AGENTAGREEMENT_element.elementTextTrim("AGENTCODE");
				String AGENTNAME = AGENTAGREEMENT_element.elementTextTrim("AGENTNAME");
				String AGREEMENTNO = AGENTAGREEMENT_element.elementTextTrim("AGREEMENTNO");
				String PERMITNOB = AGENTAGREEMENT_element.elementTextTrim("PERMITNOB");
				//请求时只有一个PRODCODE值，RISKDETAIL节点则只有一个
				List<Element> RISKDETAIL_elementList = AGENTAGREEMENT_element.elements("RISKDETAIL");
				if(AGENTCODE.equals(agentCode)){
					for (Element RISKDETAIL : RISKDETAIL_elementList) {
						String prod = RISKDETAIL.elementTextTrim("RISKCODE");
						prodSet.add(prod);
					}
				}
				Element RISKDETAIL_element = RISKDETAIL_elementList.get(0);
				String FEEMAXRATE  = RISKDETAIL_element.elementTextTrim("FEEMAXRATE");
				String FEEMINRATE  = RISKDETAIL_element.elementTextTrim("FEEMINRATE");
				double feeMaxRate = 0;
				try{
					feeMaxRate = Double.parseDouble(FEEMAXRATE) * 0.01;
				}catch(Exception e){
					feeMaxRate = 1;
					logger.info(e);
				}
				FEEMAXRATE = Double.toString(feeMaxRate);

				double feeMinRate = 0;
				try{
					feeMinRate = Double.parseDouble(FEEMINRATE) * 0.01;
				}catch(Exception e){
					feeMinRate = 0;
					logger.info(e);
				}
				FEEMINRATE = Double.toString(feeMinRate);

				Map<String,Object> AGENTAGREEMENT = new HashMap<String, Object>();
				AGENTAGREEMENT.put("AGENTCODE", AGENTCODE);//代理人代码
				AGENTAGREEMENT.put("AGREEMENTNO", AGREEMENTNO);//协议代码
				AGENTAGREEMENT.put("PERMITNOB", PERMITNOB);//资格证号
				AGENTAGREEMENT.put("AGENTNAME", AGENTNAME);//代理名称
				AGENTAGREEMENT.put("FEEMAXRATE", FEEMAXRATE);//手续费比例上限
				AGENTAGREEMENT.put("FEEMINRATE", FEEMINRATE);//手续费比例下限
				AGENTAGREEMENT.put("prodSet",prodSet);
				AGENTAGREEMENTList.add(AGENTAGREEMENT);
			}
		}else{
			throw new AppException("调用销管接口获取数据失败:" + RETURNMSG.getTextTrim());
		}
		return Result.success(AGENTAGREEMENTList);
	}
	////查询广东销售员信息
	@Override
	public Map<String, String> querySalesInfo(String COMCODE, String USERNAME,String TEAMCODE,String USERCODE) throws Exception{
		String url = Config.getProp("SALES_WEBSERVICE_URL");
		String method = "querySauserInfoByParam";
		String namespace = Config.getProp("querySauserAndTeamInfo_NAMESPACE");

		//拼接请求报文
		String reqXml ="<?xml version=\"1.0\" encoding=\"GBK\"?>\n" +
				"<XML>\n" +
				"\t<USER>\n" +
				"\t\t<COMCODE>"+COMCODE+"</COMCODE>\n" +
				"\t\t<USERNAME>"+USERNAME+"</USERNAME>\n" +
				"\t\t<USERCODE>"+USERCODE+"</USERCODE>\n" +
				"\t\t<TEAMCODE>"+TEAMCODE+"</TEAMCODE>\n" +
				"\t</USER>\n" +
				"</XML>";
		logger.info("查询广东销售员信息--》请求报文:"+reqXml);
		String respXml = "";
		//调用销管接口
		respXml = WebServiceUtil.call(reqXml, url, method, namespace);
		logger.info("查询广东销售员信息--》返回报文:"+respXml);
		Document doucument = DocumentHelper.parseText(respXml);
		Element element = doucument.getRootElement();
		Map<String, String> resultMap = new HashMap<String, String>();
		//解析报文校验查询是否成功
		    String RETURNCODE = selectSingleNodeByRoot(element , "/XML/RETURN/RETURNCODE");
			String userCode = selectSingleNodeByRoot(element , "/XML/RETURN/RETURNMSG/USERINFO/USERCODE");
			String userName = selectSingleNodeByRoot(element , "/XML/RETURN/RETURNMSG/USERINFO/USERNAME");
			String PERMITNO = selectSingleNodeByRoot(element , "/XML/RETURN/RETURNMSG/USERINFO/PERMITNO");
			String PERSONTYPE = selectSingleNodeByRoot(element , "/XML/RETURN/RETURNMSG/USERINFO/PERSONTYPE");
			String LEADERFLAG = selectSingleNodeByRoot(element ,"/XML/RETURN/RETURNMSG/USERINFO/LEADERFLAG");
		if ("".equals(RETURNCODE) || RETURNCODE.length() != 4 || (!"0000".equals(RETURNCODE) && !"0001".equals(RETURNCODE))){
			String errorInfo = element.selectSingleNode("/XML/RETURN/RETURNCODE") == null ? "系统错误 请联系管理员" : element.selectSingleNode("/XML/RETURN/RETURNCODE").getText();
			throw new AppException(errorInfo);
		}
		if("0000".equals(RETURNCODE)){
			resultMap.put("USERCODE",userCode);
			resultMap.put("USERNAME",userName);
			resultMap.put("PERSONTYPE",PERSONTYPE);
			resultMap.put("PERMITNO",PERMITNO);
			resultMap.put("LEADERFLAG",LEADERFLAG);
		}
			return resultMap;
	}

	@Override
	public String selectSingleNodeByRoot(Element root,String path){
		Node node = root.selectSingleNode(path);
		if(node==null){
			return "";
		}else{
			return node.getText();
		}
	}
}
